package com.killer.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.killer.common.util.BCryptUtil;
import com.killer.system.entity.Admin;
import com.killer.system.mapper.AdminMapper;
import com.killer.system.service.IAdminService;
import com.killer.db.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author killer
 * @since 2021-08-18
 */
@Service
public class AdminServiceImpl extends BaseServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Override
    public boolean save(Admin admin) {
        if (StringUtils.isBlank(admin.getLoginName()) || StringUtils.isBlank(admin.getPassword())) {
            throw new RuntimeException("请填写用户名和密码");
        }
        admin.setPassword(BCryptUtil.hashpw(admin.getPassword(), BCryptUtil.gensalt()));
        if (admin.getStatus() == null) {
            admin.setStatus("1");
        }
        return super.save(admin);
    }

    @Override
    public boolean login(Admin admin) {
        if (admin == null || StringUtils.isBlank(admin.getLoginName()) || StringUtils.isBlank(admin.getPassword())) {
            throw new RuntimeException("请输入用户名和密码");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loginName", admin.getLoginName());
        List<Admin> results = super.search(params);
        if (CollectionUtils.isEmpty(results)) {
            return false;
        }
        Admin result = results.get(0);
        //将id设置进去，供外面获取
        admin.setId(result.getId());
        return BCryptUtil.checkpw(admin.getPassword(),result.getPassword());
    }

    @Override
    protected LambdaQueryWrapper<Admin> createQueryWrapper(Map<String, Object> searchMap) {
        LambdaQueryWrapper<Admin> queryWrapper = Wrappers.lambdaQuery(Admin.class);
        if (searchMap.get("loginName") != null) {
            queryWrapper.eq(Admin::getLoginName, searchMap.get("loginName"));
        }
        if (searchMap.get("id") != null) {
            queryWrapper.eq(Admin::getId, searchMap.get("id"));
        }
        return queryWrapper;
    }
}
